import { Button, List, Modal } from "antd";
import { Row } from "../../components/lib";
import dayjs from "dayjs";
import { useDeleteEpic, useEpics } from "../../hooks/useEpics";
import { useEpicQueryKey, useEpicsSearchParams } from "./utils";
import { useTasks } from "../../hooks/useTasks";
import { useProjectIdInUrl, useTasksSearchParams } from "../billboard/utils";
import { Link } from "react-router-dom";

export const EpicList = () => {
  const { data: epics, isLoading: epicsLoading } = useEpics(
    useEpicsSearchParams()
  );
  const { data: allTasks, isLoading: tasksLoading } = useTasks(
    useTasksSearchParams()
  );
  const { mutateAsync: deleteEpic } = useDeleteEpic(useEpicQueryKey());
  const onConfirmDelete = (id: number) => {
    Modal.confirm({
      title: "确认删除任务组吗？",
      okText: "确认",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        return deleteEpic({ id });
      },
    });
  };

  const projectId = useProjectIdInUrl();
  const isLoading = epicsLoading || tasksLoading;
  return (
    <List
      itemLayout="vertical"
      dataSource={epics}
      loading={isLoading}
      renderItem={(epic) => (
        <List.Item key={epic.id}>
          <List.Item.Meta
            title={
              <Row between={true}>
                <span>{epic.name}</span>
                <Button type="link" onClick={() => onConfirmDelete(epic.id)}>
                  删除
                </Button>
              </Row>
            }
            description={
              <>
                <div>
                  开始时间：{dayjs(epic.start).format("YYYY年MM月DD日")}
                </div>
                <div>结束时间：{dayjs(epic.end).format("YYYY年MM月DD日")}</div>
              </>
            }
          />
          <Row gap={true}>
            {allTasks
              ?.filter((task) => task.epicId === epic.id)
              ?.map((task) => (
                <Link
                  to={`/projects/${projectId}/epic?editingTaskId=${task.id}`}
                  key={task.id}
                >
                  {task.name}
                </Link>
              ))}
          </Row>
        </List.Item>
      )}
    />
  );
};
